package com.hxh.component.business.ui.face.main;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;

import com.hxh.component.basicore.Base.topbar.ActionBarConfig;
import com.hxh.component.basicore.ui.loading.LoadingDialog;
import com.hxh.component.basicore.util.Utils;
import com.hxh.component.basicore.util.convert.JsonFactory;
import com.hxh.component.business.R;
import com.hxh.component.business.common.api.Request_StepOneInfo;
import com.hxh.component.business.ui.TopBarBaseActivity;
import com.hxh.component.business.ui.face.FaceResuleBean;
import com.hxh.component.business.ui.face.LivenessActivity;
import com.hxh.component.business.ui.face.util.ConUtil;
import com.hxh.component.business.ui.face.util.SharedUtil;
import com.hxh.component.business.utils.oss.bean.OssUpLoadResultBean;
import com.megvii.licensemanager.Manager;
import com.megvii.livenessdetection.LivenessLicenseManager;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import static android.os.Build.VERSION_CODES.M;
import static com.hxh.component.business.utils.Constant.RouterTag.VIDEO_HOME;

/**
 * Face++ 活体验证
 */
public class LoadingActivity extends TopBarBaseActivity<LoadingActivityPersenter> implements View.OnClickListener, LoadingActivityContract.V {

    private String uuid;

    private Button btn;

    private SharedUtil mSharedUtil;
    private LoadingDialog mLoadingDialog;
    private boolean mCloseDialogFlag;

    @Override
    public int getLayoutId() {
        return R.layout.layout_loading;
    }

    @Override
    public void initData(Bundle saveInstanceState) {
        init();
        netWorkWarranty();
    }

    @Override
    protected ActionBarConfig setActionBarConfig() {
        //contract_ID = getIntent().getStringExtra(DEFAULTKEY);
        return new ActionBarConfig.Builder()
                .enableBackView()
                .title("活体认证", R.color.text_default)
                .backgroundColor(R.color.white)
                .build();
    }

    @Override
    public LoadingActivityPersenter newP() {
        return new LoadingActivityPersenter();
    }


    private void init() {
        mLoadingDialog = new LoadingDialog(this, "初始化组件中");
        mSharedUtil = new SharedUtil(this);
        uuid = ConUtil.getUUIDString(this);
        btn = (Button) findViewById(R.id.loading_layout_livenessBtn);
        btn.setOnClickListener(this);
    }

    /**
     * 联网授权
     */
    private void netWorkWarranty() {
        mLoadingDialog.show();
//        btn.setVisibility(View.GONE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Manager manager = new Manager(LoadingActivity.this);
                LivenessLicenseManager licenseManager = new LivenessLicenseManager(LoadingActivity.this);
                manager.registerLicenseManager(licenseManager);
                manager.takeLicenseFromNetwork(uuid);
                d("uuid是" + uuid);
                if (licenseManager.checkCachedLicense() > 0)
                    mHandler.sendEmptyMessage(1);
                else
                    mHandler.sendEmptyMessage(2);
            }
        }).start();
    }



    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);

        String language_save = mSharedUtil.getStringValueByKey("language");
        Locale locale = getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        if (!language.equals(language_save))
            showLanguage(language);
    }

    protected void showLanguage(String language) {
        // 设置应用语言类
        Resources resources = getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        if (language.equals("zh")) {
            config.locale = Locale.SIMPLIFIED_CHINESE;
        } else {
            config.locale = Locale.ENGLISH;
        }
        resources.updateConfiguration(config, dm);
        mSharedUtil.saveStringValue("language", language);
        // freshView();
    }

    private void freshView() {
        Intent intent = new Intent(this, LoadingActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.loading_layout_livenessBtn) {
            requestCameraPerm();
        }
    }

    private void requestCameraPerm() {
        if (android.os.Build.VERSION.SDK_INT >= M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {
                //进行权限请求
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.CAMERA},
                        EXTERNAL_STORAGE_REQ_CAMERA_CODE);
            } else {
                enterNextPage();
            }
        } else {
            enterNextPage();
        }
    }

    private void enterNextPage() {

//        if (isEmpty(contract_ID)) {
//            toastShort("遇到内部错误，请返回重新开始");
//        } else {
////            getP().getContractDetails(contract_ID);//切换注释 跳过活体检测
//            startActivityForResult(new Intent(this, LivenessActivity.class), PAGE_INTO_LIVENESS);
//        }

        startActivityForResult(new Intent(this, LivenessActivity.class), PAGE_INTO_LIVENESS);
        //TODO  --------test---------
//        startActivity(LoginMainActivity.class, com.hxh.component.business.utils.Constant.RouterTag.SHOWTAG, com.hxh.component.business.utils.Constant.RouterTag.VIDEO_HOME);
//        finish();
    }

    public static final int EXTERNAL_STORAGE_REQ_CAMERA_CODE = 10;


    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        if (requestCode == EXTERNAL_STORAGE_REQ_CAMERA_CODE) {
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {// Permission Granted

                ConUtil.showToast(this, "获取相机权限失败");
            } else
                enterNextPage();
        }
    }


    private static final int PAGE_INTO_LIVENESS = 100;

    private String delta = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PAGE_INTO_LIVENESS && resultCode == RESULT_OK) {
            String error = data.getStringExtra("error");
            if (!isEmpty(error)) {
                FaceResuleBean face = JsonFactory.getFastJsonConvert().toObj(error, FaceResuleBean.class);
                toastShort(face.resulemsg, Gravity.CENTER);
            } else {
                final String delta = data.getStringExtra("delta");
                final HashMap<String, String> map = (HashMap<String, String>) data.getSerializableExtra("images");

                List<Request_StepOneInfo.FaceidPicBean> faceidPicBeanList = new ArrayList<>();
                faceidPicBeanList.clear();
                faceidPicBeanList.add(new Request_StepOneInfo.FaceidPicBean());
                faceidPicBeanList.add(new Request_StepOneInfo.FaceidPicBean());
                faceidPicBeanList.add(new Request_StepOneInfo.FaceidPicBean());
                //保存左转右转图片
                Iterator iter = map.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String key = (String) entry.getKey();
                    String val = (String) entry.getValue();

                    if (!"image_env".equals(key)){
                        com.alibaba.fastjson.JSONObject obj = com.alibaba.fastjson.JSONObject.parseObject(val);
                        OssUpLoadResultBean bean = obj.toJavaObject(obj,OssUpLoadResultBean.class);

                        Request_StepOneInfo.FaceidPicBean faceidPicBean = new Request_StepOneInfo.FaceidPicBean();
                        faceidPicBean.setBucket(bean.getBucket());
                        faceidPicBean.setObject(bean.getObject());
                        faceidPicBean.setEtag(bean.getEtag());
                        faceidPicBean.setSize(bean.getSize());
                        faceidPicBean.setMime_type(bean.getMime_type());
                        faceidPicBean.setName(bean.getName());
                        faceidPicBean.setObject_id(bean.getObject_id());
                        faceidPicBean.setIs_publice(bean.getIs_public());

                        if ("image_action1".equals(key))
                            faceidPicBeanList.set(0,faceidPicBean);
                        else if ("image_best".equals(key))
                            faceidPicBeanList.set(1,faceidPicBean);
                        else if ("image_action2".equals(key))
                            faceidPicBeanList.set(2,faceidPicBean);

//                        faceidPicBeanList.add(faceidPicBean);
//                    //获取url
//                        String mUrl = OSSUtil.getDynamicUrl_new_private(this, OSSUtil.mDefaultinitOSSResponse,
//                                bean.getBucket(), bean.getObject());
//
//                        if (!isEmpty(mUrl)) mUrl.replace("https", "http");
//                        Log.d("face++人脸识别", key + "-----------" + mUrl);
                    }
                }

//                mRequestStepOneInfo.setFaceid_pic(faceidPicBeanList);


                if (null == delta) {
                    Utils.Toast.toast("请重新验证", Gravity.CENTER);
                } else {
                    mLoadingDialog.setText("识别中");
                    mLoadingDialog.show();
                    timer.start();
                    mCloseDialogFlag = true;
                    getP().uploadFaceImg(map, delta);
                }
            }

        }
    }

    /**
     * 跳转至验证步骤相关页
     * @param routerTag
     */
    private void goRouterActivty(String routerTag) {
//        Intent intent = new Intent(this, LoginMainActivity.class);
//        intent.putExtra(com.hxh.component.business.utils.Constant.RouterTag.SHOWTAG, routerTag);
//        startActivity(intent);
    }

    @Override
    public void showFaceChecerResult(boolean iso, String msg) {
        mCloseDialogFlag = false;
        if (null != mLoadingDialog) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mLoadingDialog.close();
                }
            });
        }

        if (iso) {
//            goRouterActivty(VIDEO_HOME);
            this.finish();
        } else {
            toastShort(msg, Gravity.CENTER);
        }
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    btn.setVisibility(View.VISIBLE);
                    mLoadingDialog.close();
                    break;
                case 2:
                    Utils.Toast.toast("授权失败");
                    mLoadingDialog.close();
                    break;
            }
        }
    };

    /**
     * 判断无响应时超时关闭加载图
     */
    private CountDownTimer timer = new CountDownTimer(5 * 1000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            if (mCloseDialogFlag){
                mLoadingDialog.close();
                toastShort("图片模糊或非本人操作，请重试");
            }
        }
    };
}